﻿#region

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

#endregion

namespace HttpHandlerSpace
{
	/// <summary>
	/// Performs socket operations
	/// </summary>
	public class SocketHandler
	{
		private const int HTTP_PORT = 80;
		private const int BYTES_TO_GET = 32;
		/// <summary>
		/// Sees if a socket can be opened to a webserver, and a 200 response is retrieved
		/// </summary>
		/// <param name="server">Address of the server to retrieve</param>
		/// <returns>True if it can connect and a 200 response is returned, otherwise false</returns>
		public static bool CanHttpConnect(string server)
		{
			bool canHttpConnect = false;
			//Set up variables and String to write to the server.
			Byte[] ByteGet = Encoding.ASCII.GetBytes(string.Format("GET / HTTP/1.1\r\nHost: {0}\r\nConnection: Close\r\n\r\n", server));
			Byte[] RecvBytes = new Byte[BYTES_TO_GET];
			String strRetPage = string.Empty;

			// Get DNS host information.
			IPHostEntry hostInfo = Dns.GetHostEntry(server);
			// Get the DNS IP addresses associated with the host.
			IPAddress[] IPaddresses = hostInfo.AddressList;

			// Evaluate the socket and receiving host IPAddress and IPEndPoint. 
			int counter = 0;
			do
			{
				try
				{
					IPAddress hostAddress = IPaddresses[counter];
					IPEndPoint hostEndPoint = new IPEndPoint(hostAddress, HTTP_PORT);

					// Creates the Socket to send data over a TCP connection.
					using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
					{
						// Connect to the host using its IPEndPoint.
						s.Connect(hostEndPoint);

						if (s.Connected)
						{
							// Sent the GET request to the host.
							s.Send(ByteGet, ByteGet.Length, 0);

							int bytes = s.Receive(RecvBytes, BYTES_TO_GET, 0);
							strRetPage = strRetPage + Encoding.ASCII.GetString(RecvBytes, 0, bytes);
						}
					}
				}
				catch (SocketException)
				{ 
				}
				finally
				{
					counter++;
				}
			} while ((string.IsNullOrEmpty(strRetPage)) && (counter < IPaddresses.Length));

			if (strRetPage.Trim().StartsWith("HTTP/1.1 200"))
			{
				canHttpConnect = true;
			}

			return canHttpConnect;
		}
	}

}
